package com.sykj.springboot;

import com.alibaba.fastjson.JSON;
import com.sykj.springboot.common.utils.TimeUtils;
import com.sykj.springboot.entity.User;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootApplicationTests2 {

    @Test
    public void test555(){

    }


	@Test
	public void test222(){
        try {
            ExecutorService executor = Executors.newSingleThreadExecutor();
            //定义一个异步任务
            Future<String> future = executor.submit(()->{
                Thread.sleep(10);
                return "hello world";
            });
            int count = 1;
            //轮询获取结果
            while (true){
                count++;
                System.out.println("---"+count);
                if(future.isDone()) {
                    System.out.println("##"+future.get());
                    break;
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }






	@Test
	public void test2() throws Exception {
		ForkJoinPool pool=new ForkJoinPool();
		// 创建异步执行任务:
		CompletableFuture<Double> cf = CompletableFuture.supplyAsync(()->{
			System.out.println(Thread.currentThread()+" 开始,time->"+TimeUtils.getCurrentDateTime());
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
			}
			if(false){
				throw new RuntimeException("test");
			}else{
				System.out.println(Thread.currentThread()+" 退出,time->"+TimeUtils.getCurrentDateTime());
				return 1.2;
			}
		},pool);
		System.out.println("time->"+TimeUtils.getCurrentDateTime());
		//等待子任务执行完成
		System.out.println("run result->"+cf.get());
		System.out.println("time->"+TimeUtils.getCurrentDateTime());
	}

	@Test
	public void test4() throws Exception {
		ExecutorService executorService= Executors.newSingleThreadExecutor();
		// 创建异步执行任务:
		CompletableFuture cf = CompletableFuture.runAsync(()->{
			System.out.println(Thread.currentThread()+" start,time->"+TimeUtils.getCurrentDateTime());
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
			}
			if(false){
				throw new RuntimeException("test");
			}else{
				System.out.println(Thread.currentThread()+" exit,time->"+TimeUtils.getCurrentDateTime());
			}
		},executorService);
		System.out.println("main thread start,time->"+TimeUtils.getCurrentDateTime());
		//等待子任务执行完成
		System.out.println("run result->"+cf.get());
		System.out.println("main thread exit,time->"+TimeUtils.getCurrentDateTime());
	}


}
